#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "Logger.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

static const uint16_t gdefaultsockfd = -1;
static const int gbacklog = 8;
static const int gport = 8080;

using task_t = std::function<void()>;
class TcpEchoServer
{
private:
    // 长任务 -> sockfd -> 长链接  不太适合线程池技术
    void Service(int sockfd, InetAddr client)
    {
        char buffer[1024];
        // ⼀直进⾏IO
        while (true)
        {
            buffer[0] = 0;
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;
                LOG(LogLevel::INFO) << "client [" << client.ToString() << "] say# " << buffer;
                std::string echo_string = "server echo# ";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // read如果返回值是0，表⽰读到了⽂件结尾(对端关闭了连接！)
            {
                LOG(LogLevel::INFO) << "client " << client.ToString() << " quit, close sockfd: " << sockfd;
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "read client " << client.ToString() << " error, sockfd: " << sockfd;
                break;
            }
        }
        close(sockfd);
    }

public:
    TcpEchoServer(uint16_t port = gport) : _listensockfd(gdefaultsockfd), _port(port)
    {
    }
    void Init()
    {
        // 1.创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0); // tcp
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create tcp socket error";
            exit(SOCK_CREATE_ERROR);
        }
        LOG(LogLevel::INFO) << "create tcp socket success: " << _listensockfd;

        // 2.bind套接字
        InetAddr addr(_port);

        if (bind(_listensockfd, addr.Addr(), addr.Length()) != 0)
        {
            LOG(LogLevel::FATAL) << "bind socker error";
            exit(SOCK_BIND_ERROR);
        }
        LOG(LogLevel::INFO) << "bind socker success: " << _listensockfd;

        // 3.listen套接字
        if (listen(_listensockfd, gbacklog) != 0) // tcp
        {
            LOG(LogLevel::FATAL) << "listen socket error";
            exit(SOCK_LISTEN_ERROR);
        }
        LOG(LogLevel::INFO) << "listen socket success: " << _listensockfd;
    }

    static void *Routine(void *arg)
    {
        ThreadData *td = static_cast<ThreadData *>(arg);
        pthread_detach(pthread_self()); // 线程分离
        td->_self->Service(td->_sockfd, td->_client);
        delete td;
        return (void*)1;

    }

    class ThreadData
    {
    public:
        int _sockfd;
        TcpEchoServer *_self;
        InetAddr _client;
        ThreadData(int sockfd, TcpEchoServer *self, InetAddr client) : _sockfd(_sockfd), _self(self), _client(client)
        {
        }
    };
    void Start()
    {
        // signal(SIGCHLD, SIG_IGN);  // 防止父进程一直阻塞等待
        while (true)
        {
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len); // 默认阻塞
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept client error";
                continue;
            }
            InetAddr clientaddr(peer);
            LOG(LogLevel::INFO) << "获取新链接成功, sockfd is : " << sockfd << "client addr: " << clientaddr.ToString();

            //  1. 单进程处理
            // Service(sockfd,clientaddr);   // 单进程

            //  2.多进程处理
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "资源不足, 创建子进程失败";
            //     exit(FORK_ERROR);
            // }
            // else if (id == 0)
            // {
            //     // 子进程
            //     close(_listensockfd);  // 防御性编程
            //     if(fork() > 0)
            //         exit(OK);

            //     // 孙子进程
            //     Service(sockfd, clientaddr);
            //     exit(OK);
            // }
            // else
            // {
            //     close(sockfd); // 1. 关闭无用fd 2. 规避fd泄漏（可用fd越来越少）
            //     pid_t rid = waitpid(id, nullptr, 0);
            //     (void)rid;

            // }

            //  3.多线程处理
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, this, clientaddr);
            // pthread_create(&tid, nullptr, Routine, (void *)td);

            //  多进程 多线程
            //  1.效率问题 connect成功才创建进程线程
            //  2.执行流个数没有上限

            //  4.线程池
            ThreadPool<task_t>::GetInstance()->Enqueue([this, sockfd, clientaddr]()
                                                       { this->Service(sockfd, clientaddr); });
        }
    }
    ~TcpEchoServer()
    {
    }

private:
    int _listensockfd;
    int _port;
};